package com.aspsine.multithreaddownload.slice;

import com.aspsine.multithreaddownload.*;
import com.aspsine.multithreaddownload.demo.DataSource;
import com.aspsine.multithreaddownload.demo.entity.AppInfo;
import com.aspsine.multithreaddownload.demo.listener.OnItemClickListener;
import com.aspsine.multithreaddownload.demo.callbacks.DownloadCallback;
import com.aspsine.multithreaddownload.demo.ui.ListItemProvider;
import com.aspsine.multithreaddownload.demo.util.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;


public class MainAbilitySlice extends AbilitySlice implements OnItemClickListener<AppInfo>
{

    private static final String TAG = MainAbilitySlice.class.getName();

    private Button start;

    private ListContainer listContainer;

    private ListItemProvider listItemProvider;

    private List<AppInfo> list;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initComponents();
        initListData();
        initProvider();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onItemClick(Component v, int position, AppInfo appInfo) {

        if(appInfo.getStatus() == AppInfo.STATUS_DOWNLOADING
                || appInfo.getStatus() == AppInfo.STATUS_CONNECTING){
            pause(appInfo.getUrl());
        }else if(appInfo.getStatus() == AppInfo.STATUS_COMPLETE){
            openfile(appInfo);
        }else if(appInfo.getStatus() == AppInfo.STATUS_INSTALLED){
            //uninstall(appInfo);
        }else {
            download(position,appInfo.getUrl() ,appInfo);
        }

    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        DownloadManager.getInstance().pauseAll();
    }

    private void download(int position, String url, AppInfo appInfo) {
        final DownloadRequest request = new DownloadRequest.Builder()
                .setName(appInfo.getName()+".jpg")
                .setUri(appInfo.getUrl())
                .setFolder(Utils.mDownloadDir)
                .build();
        HiLog.debug(new HiLogLabel(3, 0, "transferData"),
                "File dir is exists "+Utils.mDownloadDir);
        DownloadManager.getInstance().download(request,url,new DownloadCallback(position,appInfo,listContainer,listItemProvider));
    }

    private void uninstall(AppInfo appInfo) {

        Utils.unInstallApp(getContext(),appInfo.getPackageName());
    }

    private void openfile(AppInfo appInfo) {
        listContainer.getItemProvider().notifyDataChanged();
        Intent intent = new Intent();
        intent.setParam("name",appInfo.getName());
        intent.setParam("url",appInfo.getUrl());
        present(new DownloadAbilitySlice(),intent);
    }

    public void pause(String tag){
        DownloadManager.getInstance().pause(tag);
    }

    private void initComponents() {
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        listContainer.setItemClickedListener(
                new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                AppInfo appInfo = (AppInfo) listContainer.getItemProvider().getItem(i);
                component.setAlpha(0.3f);
                listContainer.getItemProvider().notifyDataChanged();
                Intent intent = new Intent();
                intent.setParam("name",appInfo.getName());
                intent.setParam("url",appInfo.getUrl());
                present(new DownloadAbilitySlice(),intent);
            }
        });

//测试数据库是用到
//        start = (Button)findComponentById(ResourceTable.Id_start);
//        start.setClickedListener(this::start);
    }


    private void initListData() {
        list = DataSource.getInstance().getData();
    }

    private void initProvider() {
        listItemProvider = new ListItemProvider(this,list);
        listItemProvider.setOnItemClickListener(this);
        listContainer.setItemProvider(listItemProvider);
        listContainer.setReboundEffect(true);
        for(AppInfo info : list){
            DownloadInfo downloadInfo = DownloadManager.getInstance().
                    getDownloadInfo(info.getUrl());
            if(null !=downloadInfo){
                info.setProgress(downloadInfo.getProgress());
                info.setDownloadPerSize(getDownloadPerSize(downloadInfo.getFinished(),
                        downloadInfo.getLength()));
                info.setStatus(AppInfo.STATUS_PAUSED);
            }
        }

    }

    private static final DecimalFormat DF = new DecimalFormat("0.00");
    private String getDownloadPerSize(long finished,long total){
        return DF.format((float)finished / (1024*1024)) + "M/" +
                DF.format((float) total / (1024 * 1024)) + "M";
    }

    public void start(Component component){
        Intent intent = new Intent();
        Operation openOption = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.aspsine.multithreaddownload")
                .withAbilityName("com.aspsine.multithreaddownload.DemoAbility")
                .build();
        present(new DemoAbilitySlice(),intent);
        intent.setOperation(openOption);
       // startAbility(intent);
    }


}
